import React, { useEffect, useRef } from "react";
import * as THREE from "three";
import { MMDAnimationHelper } from "three/examples/jsm/animation/MMDAnimationHelper.js";
import { MMDLoader } from "three/examples/jsm/loaders/MMDLoader.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

const MMDScene = ({ animations }) => {
  const containerRef = useRef(null);

  useEffect(() => {
    let scene, camera, renderer, clock;
    let frameId;
    const cameraPosition = {
      x: 0,
      y: 0,
      z: 75,
    };
    const width = window.innerWidth;
    const height = window.innerHeight;

    // 初始化场景、相机、渲染器
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 2000);
    camera.position.set(cameraPosition.x, cameraPosition.y, cameraPosition.z);
    renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
    renderer.setSize(width, height);
    renderer.setClearColor(new THREE.Color(0x000000));

    // 添加灯光
    const light = new THREE.AmbientLight(0xa0a0a0);
    scene.add(light);

    // 初始化 MMDLoader 和 MMDAnimationHelper
    const loader = new MMDLoader();
    const helper = new MMDAnimationHelper();

    let mesh;
    let currentAnimationIndex = 0;

    const playAnimation = (animationIndex) => {
      if (animations.length > 0) {
        const animation = animations[animationIndex];

        // 移除旧的 mesh 和动画
        if (mesh) {
          scene.remove(mesh);
          helper.remove(mesh);
          mesh = null;
        }

        loader.loadWithAnimation("/qque/青雀（分桦）.pmx", animation, (mmd) => {
          mesh = mmd.mesh;

          scene.add(mesh);
          helper.add(mesh, {
            animation: mmd.animation,
            physics: true,
          });

          const mixer = new THREE.AnimationMixer(mesh);
          const action = mixer.clipAction(mmd.animation);
          action.setLoop(THREE.LoopOnce);
          action.clampWhenFinished = true;
          action.reset().play();

          action.addEventListener("finished", () => {
            currentAnimationIndex =
              (currentAnimationIndex + 1) % animations.length;
            playAnimation(currentAnimationIndex); // 播放下一个动画
          });
        });
      }
    };

    playAnimation(currentAnimationIndex); // 开始播放动画

    // 初始化 OrbitControls
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.target.set(0, 10, 0);
    controls.update();

    // 添加地平面
    const planeGeometry = new THREE.PlaneGeometry(40, 40);
    const planeMaterial = new THREE.MeshBasicMaterial({ color: 0x001100 });
    const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial);
    planeMesh.rotation.x = -Math.PI / 2;
    scene.add(planeMesh);

    // 时钟
    clock = new THREE.Clock();

    // 渲染函数
    const render = () => {
      const delta = clock.getDelta();
      helper.update(delta); // 更新 MMDHelper
      renderer.render(scene, camera);
      frameId = requestAnimationFrame(render);
    };

    controls.addEventListener("change", render);

    // 挂载渲染器到 DOM
    if (containerRef.current) {
      containerRef.current.appendChild(renderer.domElement);
    }

    // 启动渲染循环
    render();

    // 组件卸载时清理资源
    return () => {
      cancelAnimationFrame(frameId);
      if (containerRef.current) {
        containerRef.current.removeChild(renderer.domElement);
      }
      if (mesh) {
        scene.remove(mesh);
        helper.remove(mesh);
      }
    };
  }, [animations]); // 依赖于 animations

  return <div ref={containerRef} id="container"></div>;
};

export default MMDScene;
